package esports

import (
	"github.com/robfig/cron/v3"
	"longmen/server/config/global"
	"longmen/server/internal/services/nami/api"
	"longmen/server/internal/services/nami/api/v5/esports/csgo"
	"longmen/server/internal/services/nami/api/v5/esports/dota2"
	"longmen/server/internal/services/nami/api/v5/esports/lol"
	"longmen/server/internal/services/nami/config"
	"sync"
)

// 任务配置Map
var allTask = []config.Task{
	{Spec: "@every 1m", Fun: PlanDelete, CronId: 0},
}

var taskMap = []api.GetTask{
	csgo.GetTaskMap,
	dota2.GetTaskMap,
	lol.GetTaskMap,
}

// SetUpTask 统一设置任务
func SetUpTask(cron *cron.Cron) {
	addConfigurableTask()

	for i := 0; i < len(taskMap); i++ {
		allTask = append(allTask, taskMap[i]()...)
	}
	for i := 0; i < len(allTask); i++ {
		taskId, err := cron.AddFunc(allTask[i].Spec, allTask[i].Fun)
		if err != nil {
			global.Log.Fatalf("add func error: %v", err)
		}
		allTask[i].CronId = taskId
	}
}

// 添加 可配置 任务,
var onceInitHandlers sync.Once

func addConfigurableTask() {
	onceInitHandlers.Do(func() {
		if config.NamiLiveEnabled() {
			global.Log.Infoln("live task enabled")
			allTask = append(allTask,
				config.Task{
					// 获取电竞的直播地址 1分钟/次
					Spec: "@every 1m", Fun: SyncLiveUrl, CronId: 0,
				},
			)
		} else {
			global.Log.Infoln("live task disabled")
		}
	})
}
